package com.mybatis.plugin;

import com.mybatis.annotation.CreateTime;
import com.mybatis.annotation.UpdateTime;
import org.apache.commons.codec.binary.Base64;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.Properties;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-24 14:45:11
 */
@Intercepts({
        // insert update delete
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class ExecutorUpdate implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorUpdate.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Method method = invocation.getMethod();
        Object[] args = invocation.getArgs();
        Object target = invocation.getTarget();
        logger.info("method = {}, args = {}, target = {}",
                method, Arrays.toString(args), target);
        Object parameter = args[1];
        logger.info("arg1 = {}, type = {}", parameter, parameter.getClass());

        MappedStatement mappedStatement = (MappedStatement) args[0];
        SqlCommandType commandType = mappedStatement.getSqlCommandType();

        Field[] fields = parameter.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(CreateTime.class)) {
                if (SqlCommandType.INSERT.equals(commandType)) {
                    field.setAccessible(true);
                    Class<?> fieldType = field.getType();
                    if (fieldType.isAssignableFrom(Date.class)) {
                        field.set(parameter, new Date());
                    } else if (fieldType.isAssignableFrom(LocalDate.class)) {
                        field.set(parameter, LocalDate.now());
                    } else if (fieldType.isAssignableFrom(LocalDateTime.class)) {
                        field.set(parameter, LocalDateTime.now());
                    } else if (fieldType.isAssignableFrom(LocalTime.class)) {
                        field.set(parameter, LocalTime.now());
                    } else if (fieldType.isAssignableFrom(Timestamp.class)) {
                        field.set(parameter, new Timestamp(System.currentTimeMillis()));
                    } else {
                        throw new IllegalArgumentException("时间类型暂不支持该类型: " + fieldType);
                    }
                }
            }
            if (field.isAnnotationPresent(UpdateTime.class)) {
                if (SqlCommandType.INSERT.equals(commandType) || SqlCommandType.UPDATE.equals(commandType)) {
                    field.setAccessible(true);
                    Class<?> fieldType = field.getType();
                    if (fieldType.isAssignableFrom(Date.class)) {
                        field.set(parameter, new Date());
                    } else if (fieldType.isAssignableFrom(LocalDate.class)) {
                        field.set(parameter, LocalDate.now());
                    } else if (fieldType.isAssignableFrom(LocalDateTime.class)) {
                        field.set(parameter, LocalDateTime.now());
                    } else if (fieldType.isAssignableFrom(LocalTime.class)) {
                        field.set(parameter, LocalTime.now());
                    } else if (fieldType.isAssignableFrom(Timestamp.class)) {
                        field.set(parameter, new Timestamp(System.currentTimeMillis()));
                    } else {
                        throw new IllegalArgumentException("时间类型暂不支持该类型: " + fieldType);
                    }
                }
            }
        }

        for (Field field : fields) {
            field.setAccessible(true);
            boolean isPassword = field.getName().equals("password");
            if (isPassword) {
                String v = (String) field.get(parameter);
                if (Objects.isNull(v)) {
                    v = "123456";
                }
                String s = Base64.encodeBase64String(v.getBytes(StandardCharsets.UTF_8));

                field.set(parameter, s);
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
